<?php

namespace app\common\model;

use think\Model;
use think\Db;

class User extends Model
{
    protected $pk = 'uid';

    // 领导人信息
    public function userParent()
    {
        return $this->hasOne('User', 'uid', 'pid')->field('uid,pid,name,tel');
    }

    /**
     * 会员列表
     *
     * @param [type] $map
     * @return void
     */
    public function getList($map = [], $size = null)
    {
        $list = $this->with('userParent')->where($map)->paginate($size);

        return $list;
    }

    /**
     * 获取推荐信息
     *
     * @param array $map
     * @param [type] $size
     * @return void
     */
    public function getTeam($map = [], $size = null)
    {
        $list = $this->with('userParent')->where($map)
            ->field('uid,pid,name,tel,create_time')->paginate($size);

        return $list;
    }


    /**
     * 获取信息
     * 
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getInfo($uid)
    {
        $info = $this->where('uid', $uid)->field('province,city,dist,pwd,s_pwd', true)->find();
        if ($info['is_agent']) {
            $info['dl_area'] = db('agent')->where('uid', $uid)->value('mer_name');
        }

        return $info;
    }

    /**
     * 添加会员
     *
     * @param [type] $data
     * @return void
     */
    public function addInfo($data)
    {
        if($this->where('tel', $data['tel'])->count()) {
            return msg_code('此手机号已注册');
        }

        $data['pwd'] = encrypt($data['pwd']);
        $data['s_pwd'] = encrypt($data['s_pwd']);
        $data['area_name'] = model('Agent')->getAreaName($data['province'], $data['city']);

        $rst = $this->save($data);
        return msg_code('操作成功', $rst);
    }

    /**
     * 重置 登录密码 支付密码
     *
     * @param [type] $uid
     * @return void
     */
    public function resetPwd($uid)
    {
        $data = [
            'pwd' => encrypt(),
            's_pwd' => encrypt()
        ];

        return $this->where('uid', $uid)->update($data);
    }

    /**
     * 变更账户信息
     *
     * @param [type] 账户数据
     * @param int   用户ID
     * @return void
     */
    public function editInfo($data, $uid = 0)
    {
        if ($uid) {
            $info = $this->where('uid', $uid)->find();
            if (isset($data['tel'])) {
                if ($info['tel'] != $data['tel']) {
                    $count = $this->where('tel', $data['tel'])->count();
                    if ($count) {
                        return msg_code('此手机号已注册');
                    }
                }
            }
            if (isset($data['p_tel']) && $data['p_tel'] != '') {
                $pid = $this->where('tel', $data['p_tel'])->value('uid');
                if ($pid) {
                    $data['pid'] = $pid;
                }
                return msg_code('此推荐人不存在');
            }
            if (isset($data['headimg'])) {
                $path = base64_imgup($data['headimg'], 'headimg');
                if (! $path) {
                    return msg_code('图片上传失败');
                }
                $data['headimg'] = $path;
            }

            if (isset($data['pwd'])) {
                $data['pwd'] = encrypt($data['pwd']);
            }

            if (isset($data['s_pwd'])) {
               $data['s_pwd'] = encrypt($data['s_pwd']);
            }
            
            $rst = $this->where('uid', $uid)->update($data);
            return msg_code('修改成功',$rst);
        }
        return msg_code('稍后重试');
    }

    /**
     * 申请成为商家
     * 
     * @param  [type] $data [description]
     * @param  [type] $uid  [description]
     * @return [type]       [description]
     */
    public function beShop($data = [], $uid)
    {
        $info = $this->where('uid', $uid)->field('is_shop,kr_coin')->find();

        if ($info['is_shop']) {
            return msg_code('您已经是商家！无需重复申请');
        }

        $need_kr = config('to_shop');
        if ($info['kr_coin'] < $need_kr) {
            return msg_code('账户余额不足');
        }

        $rst = $this->updateUserAcc($uid, -$need_kr, 'kr_coin', '升级成为商家扣除');

        if ($rst) {
            $this->where('uid', $uid)->setField('is_shop', 1);
            return msg_code('操作成功', $rst);
        }
        return msg_code('售后重试');
    }


    /**
     * 账户金币转化
     * 
     * @param  [type] $data [description]
     * @param  [type] $uid  [description]
     * @return [type]       [description]
     */
    public function coinTrans($data, $uid)
    {
        $coin = config('coin');
        $coinText = config('coinText');

        $rule = db('user_coin_trans')
            ->where('id', $data['rules_id'])->field('index,from,to,rate,mini_base,status')->find();

        // 转账规则
        $from = $coin[$rule['from']];
        $to   = $coin[$rule['to']];

        if ($rule['status']) {

            $info = $this->where('uid', $uid)->field('s_pwd,kr_coin,tg_coin,hg_coin,sc_coin')->find();

            if ($info['s_pwd'] != encrypt($data['s_pwd'])) {
                return msg_code('支付密码不正确');
            }
            if ($info[$from] < $data['num']) {
                return msg_code($coinText[$from].'余额不足！');
            }
            if ($data['num'] >= $rule['mini_base'] && $data['num'] % $rule['mini_base'] == 0) {
                Db::startTrans();
                try {
                    $this->updateUserAcc($uid, -$data['num'], $from, '转账到'.$coinText[$to]);
                    $this->updateUserAcc($uid, $data['num'], $to, $coinText[$from].'转化而来');
                    Db::commit();
                    return msg_code('转化成功', 1);
                } catch (Exception $e) {
                    Db::rollback();
                    return msg_code($e->getMessage());
                }
            }
            return msg_code('转账数目不低于'.$rule['mini_base']);
        }
        return msg_code('暂不支持对应账户转换');
    }   

    /**
     * 变更会员账户余额
     *
     * @param [type] $uid   会员id
     * @param [type] $num   数目（+、—）
     * @param [type] $acc_type  账户类型
     * @param [type] $note  备注
     * @param int $record   是否需要添加记录
     * @return void
     */
    public function updateUserAcc($uid, $num, $acc_type, $note, $record = 1)
    {
        if ($num == 0) {
            return ;
        }

        $info = $this->where('uid', $uid)->find();
        
        if ($info[$acc_type] + $num < 0) {
            return msg_code('超出账户余额');
        }
        
        $rst = $this->where('uid', $uid)->setInc($acc_type, $num);

        if ($record) {
            $acc = config('coin');
            $data = [
                'uid' => $info['uid'],
                'num' => $num,
                'acc_type' => $acc[$acc_type],
                'note' => $note,
                'create_time' => date('Y-m-d H:i:s')
            ];

            db('user_account_records')->insert($data);
        }

        if ($rst) {
            return msg_code('操作完成', 1);
        }
        return msg_code('操作失败');
    }



}
